
/*
 * Copyright (C) 2009 Archie L. Cobbs. All rights reserved.
 *
 * $Id: IntegerField.java 377 2010-03-11 20:50:18Z archie.cobbs $
 */

package org.dellroad.sidekar;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;

import org.dellroad.sidekar.util.PackedLong;
import org.dellroad.stuff.string.ParseContext;

/**
 * Integer field.
 *
 * @see org.dellroad.sidekar.annotation.SidekarField
 */
public final class IntegerField extends AtomicField<Integer> {

    IntegerField(String name, Entity<?> entity) {
        super(name, entity, Integer.class);
    }

    @Override
    public void visit(FieldSwitch fieldSwitch) {
        fieldSwitch.caseIntegerField(this);
    }

    @Override
    public void encode(DataOutputStream output, Integer value) throws IOException {
        PackedLong.write(output, value);
    }

    @Override
    public Integer decode(DataInputStream input) throws IOException {
        return (int)PackedLong.read(input);
    }

    @Override
    public String toString(Integer value) {
        return value.toString();
    }

    @Override
    public Integer fromString(ParseContext ctx) {
        return Integer.parseInt(ctx.matchPrefix("-?[0-9]+").group());
    }
}

